package com.cloudweb.oa.security;

import com.cloudweb.oa.service.OnlineUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MyLogoutHandler implements LogoutHandler {

    @Autowired
    OnlineUserService onlineUserService;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String userName;
        // 如果是 WebSecurityConfig中configure的是DaoAuthenticationProvider，则authentication取到的是org.springframework.security.core.userdetails.User
        if (authentication.getPrincipal() instanceof org.springframework.security.core.userdetails.User) {
            userName = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername();
        } else {
            userName = (String) authentication.getPrincipal();
        }
        log.info("username: {}  is offline now", userName);

        onlineUserService.doLogoutPc(request);
    }
}